package com.lxk.wx.robot.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import com.lxk.wx.robot.Bot;
import com.lxk.wx.robot.config.WechatBotConfig;
import com.lxk.wx.robot.msg.MarkdownMsg;
import com.lxk.wx.robot.msg.TextMsg;
import com.lxk.wx.robot.service.BotService;
import com.lxk.wx.robot.service.BotTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Component
@Slf4j
public class BotServiceImpl implements BotService, BotTaskService, CommandLineRunner {

    private static final BlockingQueue<String> CONTENT_QUEUS = CollUtil.newBlockingQueue(10000, false);
    @Autowired
    private WechatBotConfig wechatBotConfig;
    private final List<Bot> botList = new CopyOnWriteArrayList<>();

    @PostConstruct
    public void init() {
        Bot bot = new Bot("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + wechatBotConfig.getKey());
        botList.add(bot);
        Set<String> keys = new HashSet<>(wechatBotConfig.getKeys());
        if (CollUtil.isNotEmpty(keys)) {
            List<Bot> bots = keys.stream().map(k -> new Bot("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + k)).collect(Collectors.toList());
            botList.addAll(bots);
        }
    }

    @Override
    public List<String> pollWaifSendMessage() {
        List<String> list = new ArrayList<>(30);
        for (int i = 0; i < botList.size() * wechatBotConfig.getMaxMsgCount(); i++) {
            String poll = CONTENT_QUEUS.poll();
            if (StrUtil.isBlank(poll)) {
                break;
            }
            list.add(poll);
        }
        return list;
    }

    @Override
    public List<Bot> getAll() {
        return botList;
    }

    @Override
    public void addSendText(String content) {
        if (StrUtil.isBlank(content)) {
            return;
        }
        try {
            TextMsg textMsg = new TextMsg();
            textMsg.setContent(content);
            textMsg.setMentionedList(Collections.singletonList("@all"));
            CONTENT_QUEUS.offer(content);
        } catch (Exception e) {
            log.error("机器人发送消息失败", e);
        }
    }

    @Async
    @Override
    public void sendText(String content) {
        if (StrUtil.isBlank(content)) {
            return;
        }
        try {
            TextMsg textMsg = new TextMsg();
            textMsg.setContent(content);
            textMsg.setMentionedList(Collections.singletonList("@all"));
            Bot bot = getRandomBot();
            bot.send(textMsg);
        } catch (Exception e) {
            log.error("机器人发送消息失败", e);
        }
    }


    @Async
    @Override
    public void sendText(String content, String webHook) {
        if (StrUtil.isBlank(content)) {
            return;
        }
        try {
            webHook = StrUtil.trim(webHook);
            TextMsg textMsg = new TextMsg();
            textMsg.setContent(content);
            textMsg.setMentionedList(Collections.singletonList("@all"));
            new Bot(webHook).send(textMsg);
        } catch (Exception e) {
            log.error("机器人发送消息失败", e);
        }
    }

    @Async
    @Override
    public void sendMarkdown(String content) {
        MarkdownMsg markdownMsg = new MarkdownMsg();
//        markdownMsg.setContent("实时新增用户反馈<font color=\"warning\">132例</font>，请相关同事注意。\n" +
//                "         >类型:<font color=\"comment\">用户反馈</font>\n" +
//                "         >普通用户反馈:<font color=\"comment\">117例</font>\n" +
//                "         >VIP用户反馈:<font color=\"comment\">15例</font>");
        markdownMsg.setContent(content);
        getRandomBot().send(markdownMsg);
    }


    private Bot getRandomBot() {
        if (botList.size() == 1) {
            return botList.get(0);
        }
        Bot bot = botList.get(RandomUtil.randomInt(botList.size()));
        return bot;
    }


    @Override
    public void run(String... args) throws Exception {
        log.info("初始化企业微信机器人成功:{}", wechatBotConfig);
//        for (int i = 0; i < 60; i++) {
//            this.addSendText(i+"");
//        }
    }
}
